<template>
  <el-card class="connection-config" shadow="hover">
    <template #header>
      <div class="card-header">
        <el-icon class="header-icon">
          <Connection />
        </el-icon>
        <span class="header-title">Kafka连接配置</span>
        <el-tag 
          :type="connectionStatus.connected ? 'success' : 'info'"
          effect="dark"
          size="small"
        >
          {{ connectionStatus.connected ? '已连接' : '未连接' }}
        </el-tag>
      </div>
    </template>

    <el-form 
      :model="form" 
      :rules="rules" 
      ref="formRef"
      label-width="140px"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务器地址" prop="bootstrap_servers">
            <el-input
              v-model="form.bootstrap_servers"
              placeholder="localhost:9092"
              :disabled="connectionStatus.connected"
            >
              <template #prefix>
                <el-icon><Server /></el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="安全协议" prop="security_protocol">
            <el-select
              v-model="form.security_protocol"
              placeholder="选择安全协议"
              :disabled="connectionStatus.connected"
              style="width: 100%"
            >
              <el-option label="PLAINTEXT" value="PLAINTEXT" />
              <el-option label="SASL_PLAINTEXT" value="SASL_PLAINTEXT" />
              <el-option label="SSL" value="SSL" />
              <el-option label="SASL_SSL" value="SASL_SSL" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- SASL配置 -->
      <el-collapse v-if="needSasl" v-model="saslCollapse">
        <el-collapse-item title="SASL认证配置" name="sasl">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="认证机制" prop="sasl_mechanism">
                <el-select
                  v-model="form.sasl_mechanism"
                  placeholder="选择认证机制"
                  :disabled="connectionStatus.connected"
                  style="width: 100%"
                >
                  <el-option label="PLAIN" value="PLAIN" />
                  <el-option label="SCRAM-SHA-256" value="SCRAM-SHA-256" />
                  <el-option label="SCRAM-SHA-512" value="SCRAM-SHA-512" />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="用户名" prop="sasl_plain_username">
                <el-input
                  v-model="form.sasl_plain_username"
                  placeholder="输入用户名"
                  :disabled="connectionStatus.connected"
                />
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="密码" prop="sasl_plain_password">
                <el-input
                  v-model="form.sasl_plain_password"
                  type="password"
                  placeholder="输入密码"
                  :disabled="connectionStatus.connected"
                  show-password
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>
      </el-collapse>

      <!-- 操作按钮 -->
      <el-form-item style="margin-top: 20px;">
        <el-button-group>
          <el-button
            type="primary"
            :loading="testing"
            @click="testConnection"
            :disabled="connectionStatus.connected"
          >
            <el-icon><Link /></el-icon>
            测试连接
          </el-button>
          
          <el-button
            v-if="!connectionStatus.connected"
            type="success"
            :loading="connecting"
            @click="connect"
          >
            <el-icon><Connection /></el-icon>
            连接
          </el-button>
          
          <el-button
            v-else
            type="danger"
            :loading="disconnecting"
            @click="disconnect"
          >
            <el-icon><Close /></el-icon>
            断开连接
          </el-button>
        </el-button-group>
      </el-form-item>
    </el-form>

    <!-- 连接信息 -->
    <el-alert
      v-if="connectionStatus.connected"
      title="连接成功"
      :description="`已连接到: ${connectionStatus.bootstrap_servers}`"
      type="success"
      :closable="false"
      show-icon
      style="margin-top: 16px;"
    />
  </el-card>
</template>

<script>
import { ref, reactive, computed, watch } from 'vue'
import { useKafkaStore } from '@/stores/kafka'
import { ElMessage, ElNotification } from 'element-plus'

export default {
  name: 'ConnectionConfig',
  emits: ['connection-changed'],
  setup(props, { emit }) {
    const kafkaStore = useKafkaStore()
    const formRef = ref()
    
    // 表单数据
    const form = reactive({
      bootstrap_servers: 'localhost:9092',
      security_protocol: 'PLAINTEXT',
      sasl_mechanism: 'PLAIN',
      sasl_plain_username: '',
      sasl_plain_password: ''
    })

    // 连接状态
    const connectionStatus = ref({
      connected: false,
      bootstrap_servers: null
    })

    // 加载状态
    const testing = ref(false)
    const connecting = ref(false)
    const disconnecting = ref(false)

    // SASL配置折叠面板
    const saslCollapse = ref(['sasl'])

    // 表单验证规则
    const rules = {
      bootstrap_servers: [
        { required: true, message: '请输入服务器地址', trigger: 'blur' }
      ],
      security_protocol: [
        { required: true, message: '请选择安全协议', trigger: 'change' }
      ],
      sasl_mechanism: [
        { required: true, message: '请选择认证机制', trigger: 'change' }
      ],
      sasl_plain_username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      sasl_plain_password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
      ]
    }

    // 计算属性
    const needSasl = computed(() => {
      return form.security_protocol === 'SASL_PLAINTEXT' || 
             form.security_protocol === 'SASL_SSL'
    })

    // 监听安全协议变化
    watch(() => form.security_protocol, (newVal) => {
      if (newVal === 'SASL_PLAINTEXT' || newVal === 'SASL_SSL') {
        saslCollapse.value = ['sasl']
      } else {
        saslCollapse.value = []
        form.sasl_mechanism = 'PLAIN'
        form.sasl_plain_username = ''
        form.sasl_plain_password = ''
      }
    })

    // 测试连接
    const testConnection = async () => {
      if (!await validateForm()) return

      testing.value = true
      
      try {
        const response = await kafkaStore.testConnection(form)
        
        if (response.data.connected) {
          ElMessage.success('连接测试成功')
          ElNotification({
            title: '连接测试成功',
            message: `成功连接到 ${form.bootstrap_servers}`,
            type: 'success'
          })
        } else {
          ElMessage.error(response.data.error || '连接测试失败')
          ElNotification({
            title: '连接测试失败',
            message: response.data.error || '无法连接到Kafka服务器',
            type: 'error'
          })
        }
      } catch (error) {
        ElMessage.error(error.message || '连接测试失败')
        ElNotification({
          title: '连接测试失败',
          message: error.message || '发生未知错误',
          type: 'error'
        })
      } finally {
        testing.value = false
      }
    }

    // 连接
    const connect = async () => {
      if (!await validateForm()) return

      connecting.value = true
      
      try {
        const response = await kafkaStore.connect(form)
        
        if (response.success) {
          connectionStatus.value = response.data
          ElMessage.success('连接成功')
          ElNotification({
            title: '连接成功',
            message: `已连接到 ${form.bootstrap_servers}`,
            type: 'success'
          })
          emit('connection-changed', response.data)
        }
      } catch (error) {
        ElMessage.error(error.message || '连接失败')
        ElNotification({
          title: '连接失败',
          message: error.message || '无法连接到Kafka服务器',
          type: 'error'
        })
      } finally {
        connecting.value = false
      }
    }

    // 断开连接
    const disconnect = async () => {
      disconnecting.value = true
      
      try {
        const response = await kafkaStore.disconnect()
        
        if (response.success) {
          connectionStatus.value = {
            connected: false,
            bootstrap_servers: null
          }
          ElMessage.success('已断开连接')
          emit('connection-changed', connectionStatus.value)
        }
      } catch (error) {
        ElMessage.error(error.message || '断开连接失败')
      } finally {
        disconnecting.value = false
      }
    }

    // 表单验证
    const validateForm = async () => {
      try {
        await formRef.value.validate()
        return true
      } catch (error) {
        ElMessage.warning('请检查表单填写')
        return false
      }
    }

    // 初始化连接状态
    const checkConnectionStatus = async () => {
      try {
        const response = await kafkaStore.getConnectionStatus()
        if (response.success) {
          connectionStatus.value = response.data
          if (response.data.connected) {
            emit('connection-changed', response.data)
          }
        }
      } catch (error) {
        console.error('检查连接状态失败:', error)
      }
    }

    // 组件挂载时检查连接状态
    checkConnectionStatus()

    return {
      form,
      formRef,
      rules,
      connectionStatus,
      testing,
      connecting,
      disconnecting,
      needSasl,
      saslCollapse,
      testConnection,
      connect,
      disconnect
    }
  }
}
</script>

<style scoped>
.connection-config {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.header-icon {
  margin-right: 8px;
  color: #409eff;
}

.header-title {
  font-weight: 600;
  flex: 1;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-button-group {
  display: flex;
  gap: 8px;
}

.el-collapse {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 16px;
}

.el-collapse-item {
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .el-row {
    flex-direction: column;
  }
  
  .el-col {
    width: 100% !important;
    margin-bottom: 16px;
  }
}
</style> 